package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.JsonObject;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class WechatServiceImpl implements WechatService {
    private static final String URL_REQUESt = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    private static final String URL_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    private static final String URL_PHONE = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


    @Value("${wechat.appId}")
    private String appid;

    @Value("${wechat.appSecret}")
    private String secret;

    @Override
    public String getOpenid(String code){


        Map<String,Object> paramMap = getConfigApi();
        paramMap.put("js_code",code);


        String result = HttpUtil.get(URL_REQUESt ,paramMap);

        JSONObject jsonObject = JSONUtil.parseObj(result);

        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){

            throw new RuntimeException(jsonObject.getStr("errmsg"));

        }
        String openid = jsonObject.getStr("openid");
        return openid;

    }

    private Map<String,Object> getConfigApi(){
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("appid",appid);
        dataMap.put("secret",secret);
        return dataMap;
    }


    @Override
    public String getPhone(String code) {
        String token = getToken();
        String url = URL_PHONE+token;
        log.info(url);
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("code",code);

        String result = HttpUtil.post(url, JSONUtil.toJsonStr(dataMap));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject.getInt("errcode")!=0){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }

    private String getToken(){
        Map<String,Object> paramMap = getConfigApi();
        String result = HttpUtil.get(URL_TOKEN,paramMap);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new BaseException(jsonObject.getStr("errmsg"));
        }
        String token = jsonObject.getStr("access_token");
        return token;
    }





}

